package servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jdk.nashorn.api.tree.SimpleTreeVisitorES5_1;

import java.io.IOException;

@WebServlet("/loginservlet")
public class loginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");
        /*获取生产的验证码*/
        HttpSession session = req.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        session.removeAttribute("checkCode_session");
        if(checkCode_session!=null && checkCode_session.equalsIgnoreCase(checkCode)){
            if("zhangsan".equals(username)&&"123".equals(password)){//需要调用数据库
                /*重定向到success.jsp
                * 重定向是两次请求
                * session能够共享多次请求
                *
                * */
                session.setAttribute("username",username);
                resp.sendRedirect(req.getContextPath()+"/success.jsp");
            }else{
                req.setAttribute("login_error","用户名或密码错误");
                /*验证码不正确 需要请求转发*/
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }else{
            /*验证码提示错误 提示信息存到request域还是session域*/
            req.setAttribute("cc_error","验证码错误");
            /*验证码不正确 需要请求转发*/
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
